<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>ZFrankLin WebSocket Chat</title>
    <style>
        /* 全局样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f7fa;
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #4a90e2;
        }

        /* 连接区域样式 */
        .connect-area {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }

        #usernameInput {
            width: 70%;
            padding: 10px 15px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            margin-right: 10px;
        }

        #usernameInput:focus {
            outline: none;
            border-color: #4a90e2;
        }

        button {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            background-color: #4a90e2;
            color: white;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #3a80d2;
        }

        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        #status {
            margin-top: 15px;
            padding: 8px 15px;
            border-radius: 4px;
            font-size: 13px;
        }

        #status.connected {
            background-color: #e6f7ee;
            color: #00875a;
        }

        #status.disconnected {
            background-color: #fff2f0;
            color: #e53e3e;
        }

        /* 消息区域样式 */
        .message-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
            height: 400px;
            overflow-y: auto;
        }

        #messages {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        /* 消息气泡基础样式 */
        .message {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 18px;
            line-height: 1.4;
            position: relative;
        }

        /* 接收消息（左对齐） */
        .message.received {
            align-self: flex-start;
            background-color: #f1f1f1;
        }

        /* 发送消息（右对齐） */
        .message.sent {
            align-self: flex-end;
            background-color: #4a90e2;
            color: white;
        }

        /* 消息元信息（用户名和时间） */
        .message-meta {
            font-size: 11px;
            margin-bottom: 5px;
            opacity: 0.8;
        }

        /* 输入区域样式 */
        .input-area {
            display: flex;
            gap: 10px;
        }

        #messageInput {
            flex: 1;
            padding: 12px 15px;
            border: 2px solid #ddd;
            border-radius: 25px;
            font-size: 14px;
        }

        #messageInput:focus {
            outline: none;
            border-color: #4a90e2;
        }

        .input-area button {
            border-radius: 25px;
            padding: 0 25px;
        }
    </style>
</head>
<body>
<h1>ZFrankLin WebSocket Chat</h1>

<!-- 连接区域 -->
<div class="connect-area">
    <input type="text" id="usernameInput" placeholder="请输入用户名">
    <button onclick="connect()">连接服务器</button>
    <div id="status" class="disconnected">未连接</div>
</div>

<!-- 消息显示区域 -->
<div class="message-container">
    <div id="messages"></div>
</div>

<!-- 输入区域 -->
<div class="input-area">
    <input type="text" id="messageInput" placeholder="输入消息...">
    <button onclick="sendMessage()">发送</button>
</div>

<script>
    let socket;
    let currentUsername; // 存储当前用户名，用于区分发送者

    function connect() {
        const usernameInput = document.getElementById('usernameInput');
        currentUsername = usernameInput.value.trim();

        if (!currentUsername) {
            alert('请输入用户名！');
            return;
        }

        // 替换为你的服务端IP
        socket = new WebSocket(`ws:/192.168.1.106:8080/ws?username=${encodeURIComponent(currentUsername)}`);

        socket.onopen = () => {
            console.log('连接已建立');
            document.getElementById('status').textContent = `已连接（用户名：${currentUsername}）`;
            document.getElementById('status').className = 'connected';

            // 禁用输入框和按钮
            usernameInput.disabled = true;
            document.querySelector('button[onclick="connect()"]').disabled = true;
        };

        socket.onmessage = (event) => {
            const messagesDiv = document.getElementById('messages');
            // 假设服务端返回的消息格式为：{ username: 'xxx', content: 'xxx', time: 'xxx' }
            try {
                console.log('收到原始数据:', event.data); // 新增：打印原始数据
                const messageData = JSON.parse(event.data);
                console.log('解析后的数据:', messageData); // 新增：打印解析结果
                // 判断是自己发送的还是接收的消息
                const isSent = messageData.username === currentUsername;
                const messageClass = isSent ? 'message sent' : 'message received';

                // 构建消息HTML
                const messageHtml = `
                        <div class="${messageClass}">
                            <div class="message-meta">
                                ${messageData.username} · ${messageData.time}
                            </div>
                            ${messageData.content}
                        </div>
                    `;
                messagesDiv.innerHTML += messageHtml;
                // 自动滚动到底部
                // messagesDiv.scrollTop = messagesDiv.scrollHeight;

                // 优化：确保DOM渲染完成后再滚动
                requestAnimationFrame(() => {
                    messagesDiv.scrollTop = messagesDiv.scrollHeight;
                });


            } catch (e) {
                // 如果服务端返回的不是JSON，直接显示文本
                messagesDiv.innerHTML += `<div class="message received">${event.data}</div>`;
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        };

        socket.onclose = () => {
            document.getElementById('status').textContent = '已断开';
            document.getElementById('status').className = 'disconnected';
        };

        socket.onerror = (error) => {
            console.error('WebSocket错误:', error);
            alert('连接错误，请检查服务是否运行');
        };
    }

    function sendMessage() {
        const input = document.getElementById('messageInput');
        const content = input.value.trim();

        if (!content || !socket) return;

        // 发送JSON格式消息（包含用户名和内容）
        const messageData = {
            username: currentUsername,
            content: content,
            time: new Date().toLocaleTimeString() // 客户端时间
        };
        socket.send(JSON.stringify(messageData));
        input.value = '';
        // 发送后立即尝试滚动到底部（防止服务器转发延迟）
        requestAnimationFrame(() => {
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        });
    }

    // 支持按Enter发送消息
    document.getElementById('messageInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
</script>
</body>
</html>